<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/5/22
 * Time: 11:11
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\admin\controller;


use app\admin\business\AdminUser as BusObj;
use app\common\lib\Show;
use app\common\lib\Status;
use think\App;
use think\captcha\facade\Captcha;
use think\facade\Session;
use think\facade\View;

class Login extends AdminBase
{
    protected $busObj = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->busObj = new BusObj();
    }

    /**
     * @return string|\think\response\Redirect
     */
    public function index()
    {
        $getLogin = Session::get(config('admin.session_admin'));
        if ($getLogin) {
            return redirect((string)url('index/index'));
        }
        return View::fetch();
    }

    /**
     * 登录验证码
     * @return \think\Response
     */
    public function verify()
    {
        return Captcha::create('login');
    }

    /**
     * 登录操作
     * @return \think\response\Json
     */
    public function checkLogin()
    {
        if (!$this->request->isPost()) {
            return Show::json_show(Status::Error, "请求方式错误");
        }
        $username = $this->request->param('username', '', 'trim');
        $password = $this->request->param('password', '', 'trim');
        $captcha = $this->request->param('captcha', '', 'trim');
        $data = [
            "username" => $username,
            "password" => $password,
            "captcha" => $captcha
        ];
        try {
            $result = $this->busObj->checkLogin($data);
        } catch (\Exception $e) {
            return Show::json_show(Status::Error, $e->getMessage());
        }
        if ($result) {
            return Show::json_show(Status::Success, "登录成功");
        } else {
            return Show::json_show(Status::Error, "登录失败");
        }
    }

    /**
     * 退出登录
     * @return \think\response\Json
     */
    public function logout()
    {
        Session::set(config('admin.session_admin'), null);
        return Show::json_show(Status::Success, "退出成功");
    }
}